<template>
  <div class="app-container">
    <el-button type="primary" @click="addRole">添加</el-button>
    <el-table v-loading="listLoading" :data="rolePageData.records" border style="width: 100%">
      <el-table-column fixed="left" label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEditAuthShow(scope.row)">权限</el-button>
          <el-button type="text" size="small" @click="handleUpdateShow(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="roleName" label="名称" width="200" />
      <el-table-column prop="roleDesc" label="描述" width="200" />
      <el-table-column prop="createBy" label="创建人" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column prop="updateBy" label="更新人" width="100" />
      <el-table-column prop="updateTime" label="更新时间" width="160" />
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next, sizes, total, jumper"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="rolePageData.size"
      :total="rolePageData.total"
      @current-change="fetchData"
    />
    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <el-form ref="RoleForm" :model="formData" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="formData.roleName" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="formData.roleDesc" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveFormData">保存</el-button>
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="编辑权限" :visible.sync="dialogAuthFormVisible" @opened="handleEditAuthShowEnd">
      角色：{{ editRoleName }}
      <el-tabs v-model="activeAuthTabName">
        <el-tab-pane label="角色权限管理" name="roleAuth">
          <el-tree
            ref="roleAuthTree"
            :data="allMenuAuth"
            show-checkbox
            node-key="menuId"
            default-expand-all
            :expand-on-click-node="false"
          >
            <span slot-scope="{ data }" class="custom-tree-node">
              <span>{{ data.menuName }}{{ data.menuAuth }}</span>
            </span>
          </el-tree>
          <el-form label-width="80px">
            <el-form-item>
              <el-button type="primary" @click="saveRoleAuth">保存</el-button>
              <el-button @click="dialogAuthFormVisible = false">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="角色用户管理" name="roleUser">
          <el-form label-width="80px">
            <el-form-item>
              <el-button type="primary" @click="deleteUserForRole">删除用户</el-button>
              <el-select
                v-model="editRoleUser"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请输入用户名查找需要添加的账号"
                :remote-method="remoteSearchUserForAddRoleUser"
                :loading="loadingForSearchUserForAddRoleUser"
              >
                <el-option
                  v-for="item in searchUserForAddRoleUser"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                />
              </el-select>
              <el-button type="primary" @click="addUserForRole">添加用户</el-button>
            </el-form-item>
          </el-form>
          <el-table
            ref="roleUserTable"
            :data="roleUserPageData.records"
            border
            style="width: 100%"
          >
            <el-table-column
              type="selection"
              width="55"
            />
            <el-table-column
              prop="userName"
              label="账号"
              width="180"
            />
            <el-table-column
              prop="userEmail"
              label="邮箱"
              width="180"
            />
            <el-table-column
              prop="userMobile"
              label="手机"
            />
          </el-table>
          <el-pagination
            background
            layout="prev, pager, next, sizes, total, jumper"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="roleUserPageData.size"
            :total="roleUserPageData.total"
            @current-change="fetchRoleUserData"
            @size-change="handleSizeChange"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import { getUserByRole, getList as getUserList } from '@/api/sys/user'
import { getList, saveRole, saveRoleAuth, addRoleUser, deleteRoleUserByRole, deleteRole } from '@/api/sys/role'
import { getRoleMenu, getAllMenu } from '@/api/sys/menu'
import { getTargetKeyValueFromSource } from '@/utils/easyUtils'
import { Message } from 'element-ui'

export default {
  data() {
    return {
      dialogFormVisible: false,
      dialogAuthFormVisible: false,
      listLoading: true,
      editRoleUser: [],
      loadingForSearchUserForAddRoleUser: false,
      searchUserForAddRoleUser: [],
      editRoleName: '',
      editRoleId: 0,
      rolePageData: {
        records: [],
        size: 10,
        total: 0,
        current: 1
      },
      roleUserPageData: {
        records: [],
        size: 10,
        total: 0,
        current: 1
      },
      activeAuthTabName: 'roleAuth',
      allMenuAuth: [],
      roleUserTable: [],
      formData: {
        roleId: 0,
        roleName: '',
        roleDesc: ''
      }
    }
  },
  created() {
    this.fetchData(1)
  },
  methods: {
    handleSizeChange(val) {
      this.rolePageData.size = val
      this.fetchData(1)
    },
    fetchData(current) {
      this.rolePageData.current = current
      this.rolePageData.records = []
      this.listLoading = true
      getList({}, this.rolePageData)
        .then(response => {
          this.rolePageData = getTargetKeyValueFromSource(this.rolePageData, response.data)
          this.listLoading = false
        })
        .catch(err => {
          this.listLoading = false
          console.log(err)
        })
    },
    fetchRoleUserData(current) {
      this.roleUserPageData.current = current
      this.roleUserPageData.records = []
      this.listLoading = true
      this.roleUserPageData.roleId = this.editRoleId
      getUserByRole(this.roleUserPageData).then(response => {
        this.roleUserPageData = response.data
      })
      getUserByRole(this.roleUserPageData)
        .then(response => {
          this.rolePageData = getTargetKeyValueFromSource(this.rolePageData, response.data)
          this.listLoading = false
        })
        .catch(err => {
          this.listLoading = false
          console.log(err)
        })
    },
    handleUpdateShow(row) {
      this.formData = getTargetKeyValueFromSource(this.formData, row)
      this.dialogFormVisible = true
    },
    handleEditAuthShowEnd() {
      this.$refs.roleAuthTree.setCheckedKeys([])
      this.roleUserTable = []
      getAllMenu().then(response => {
        this.allMenuAuth = response.data
        getRoleMenu({ 'roleId': this.editRoleId }).then(response => {
          if (response.data && response.data.length > 0) {
            response.data.forEach((i, n) => {
              const node = this.$refs.roleAuthTree.getNode(i.menuId)
              if (node.isLeaf) {
                this.$refs.roleAuthTree.setChecked(node, true)
              }
            })
          }
        })
      })
      getUserByRole({ 'roleId': this.editRoleId }).then(response => {
        this.roleUserPageData = response.data
      })
    },
    handleDelete(row) {
      this.$confirm('确定删除角色？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole({ 'roleId': row.roleId }).then(response => {
          this.fetchData(1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditAuthShow(row) {
      this.dialogAuthFormVisible = true
      this.editRoleName = row.roleName
      this.editRoleId = row.roleId
    },
    saveFormData() {
      this.formData.children = []
      saveRole(this.formData).then(response => {
        this.dialogFormVisible = false
        this.fetchData(1)
      })
    },
    saveRoleAuth() {
      const auth = this.$refs.roleAuthTree.getCheckedKeys().concat(this.$refs.roleAuthTree.getHalfCheckedKeys())
      const params = {
        roleId: this.editRoleId,
        auths: auth
      }
      saveRoleAuth(params).then(response => {
        this.dialogAuthFormVisible = false
      })
    },
    addUserForRole() {
      const params = {
        roleId: this.editRoleId,
        userIds: this.editRoleUser
      }
      addRoleUser(params).then(response => {
        console.log(response)
        Message({
          message: '保存成功',
          type: 'info',
          duration: 5 * 1000
        })
      })
    },
    deleteUserForRole() {
      const userIds = []
      this.$refs.roleUserTable.selection.forEach((item) => {
        userIds.push(item.userId)
      })
      const params = {
        roleId: this.editRoleId,
        userIds
      }
      deleteRoleUserByRole(params).then(response => {
        Message({
          message: '删除成功',
          type: 'info',
          duration: 5 * 1000
        })
      })
    },
    addRole() {
      this.formData = getTargetKeyValueFromSource(this.formData, {
        roleId: 0,
        roleName: '',
        roleDesc: ''
      })
      this.dialogFormVisible = true
    },
    remoteSearchUserForAddRoleUser(query) {
      if (query) {
        this.loadingForSearchUserForAddRoleUser = true
        getUserList({ 'userName': query }).then(response => {
          this.loadingForSearchUserForAddRoleUser = false
          this.searchUserForAddRoleUser = response.data.records
        })
      } else {
        this.searchUserForAddRoleUser = []
      }
    }
  }
}
</script>
